const { queryArticlePassedApprovalList, queryArticleTypeTree } = require('../../api/article')
const { to, openLoading, closeLoading, routeWithToken, getEventData } = getApp()
const { STORAGE_CONSTANT  } = require('../../constant/index')
const { clearEmptyKey } = require('../../utils/clearEmptyKey')
Page({
  data: {
    dataList: [],
    filterData: {},
    ishaveData: 'start',
    loadingType: '',
    pagination: {
      page: 1,
      limit: 10
    },
    searchValue: {}
  },

  onLoad() {
    this.resetData();
    this.getPromise();
  },

  async getPromise() {
    openLoading()
    this.setData({
      ishaveData: 'start'
    })
    Promise.all([this.getQueryArticleTypeTree(), this.getArticleData(false)])
    closeLoading();
    wx.nextTick(() => {
      this.setData({
        ishaveData: 'end'
      })
    })
  },

  async getQueryArticleTypeTree() {
    const [err, data] = await to(queryArticleTypeTree({}));

    if (!err) {
      this.setData({
        filterData: data
      })
    }
  },

  async getArticleData(open = true) {
    const params = {
      queryCondition: this.data.searchValue.inputVal || '',
      articleTypeId: this.data.searchValue.swiperValue || '',
      ...this.data.pagination
    }
    clearEmptyKey(params);
    open && openLoading()
    const [err, data] = await to(queryArticlePassedApprovalList(params))
    closeLoading()

    if (!err) {
      const {
        dataList
      } = this.data
      this.setData({
        dataList: dataList.concat(data.dataList),
        total: data.total
      })

      if (data.total === 0) {
        this.setData({
          loadingType: 'empty'
        })
        return
      }

      if (this.data.dataList.length >= data.total) {
        this.setData({
          loadingType: 'end'
        })
      }
    }
  },

  handleSearchChange(event) {
    this.setData({
      searchValue: event.detail
    })
    this.resetData()
    this.getArticleData()
  },

  resetData() {
    this.setData({
      ['pagination.page']: 1,
      dataList: [],
      loadingType: '',
      total: 0
    })
  },

  handleScrolltolower() {
    const {
      total,
      pagination,
      dataList
    } = this.data

    if (dataList.length < total) {
      let page = pagination.page;
      page++
      this.setData({
        loadingType: 'loading',
        ['pagination.page']: page
      })
      this.getArticleData(false)
    }
  },

  handleToRoute(event) {
    wx.setStorageSync(STORAGE_CONSTANT.articsRouteName, event.detail)
    routeWithToken('../know-ledge-detail/index')
  },
})